﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Hopscotch.Common;
using Hopscotch.Presentation.Common;
using Hopscotch.Presentation.Common.Data;
using Hopscotch.Presentation.Common.Threading;


namespace Hopscotch.Application.Shell
{
    /// <summary>
    /// App Controller
    /// </summary>
    /// <remarks>There should be a single instance of this controller</remarks>
    public class AppController : IAppController
    {
        private readonly IDispatcher mainDispatcher;

        private Dictionary<Guid, object> activeWorkspaces;
        private ObservableCollection<ToolMenuItem> toolMenuItems;

        public AppController(IDispatcher mainDispatcher, EnvironmentKey environmentKey)
        {
            this.mainDispatcher = mainDispatcher;
            this.CurrentEnvironment = environmentKey;

            activeWorkspaces = new Dictionary<Guid, object>();
            toolMenuItems = new ObservableCollection<ToolMenuItem>();
        }

        public EnvironmentKey CurrentEnvironment { get; private set; }

        public ObservableCollection<ToolMenuItem> ToolMenuItems
        {
            get
            {
                return toolMenuItems;
            }
        }

        public void RegisterTool(string caption, Type tool, Uri imageUri)
        {
            ToolMenuItem toolCmd = new ToolMenuItem()
            {
                Header = caption,
                ViewType = tool,
                ImageUri = imageUri
            };

            ToolMenuItems.Add(toolCmd);
        }

        public void RegisterShell(IShellContext shell)
        {
            activeWorkspaces.Add(shell.InstanceId, null);
        }

        void IAppController.CloseShell(IShellContext shell)
        {
            if (activeWorkspaces.ContainsKey(shell.InstanceId))
            {
                activeWorkspaces.Remove(shell.InstanceId);
            }

            if (activeWorkspaces.Count == 0)
            {
                ((IAppController)this).Exit();
            }
        }

        void IAppController.Exit()
        {
            //Needs to be run on main dispatcher thread
            Action shutdown = System.Windows.Application.Current.Shutdown;
            mainDispatcher.Invoke(shutdown);
        }
    }
}
